package com.zsr.chapter05.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author zsr
 * @Description Cookie对象和常用API介绍
 * @Date 2021/4/21 23:39
 */
public class Demo1 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取所有的cookie并放入一个数组
        Cookie[] cookies = request.getCookies();
        String product=null;
        //遍历cookies数组
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("product")){
                product=cookie.getValue();
                break;
            }
        }
        PrintWriter out = response.getWriter();
        if(product==null){
            out.print("No cookie");
            //创建cookie，并发送给客户端
            Cookie cookie=new Cookie("product" , "IPhone7");
            response.addCookie(cookie);
        }else{
            out.print("您上次浏览的商品为："+product);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}
